package com.jvup.common.utils;

import android.app.Application;
import android.content.Context;
import android.text.TextUtils;

import com.jvup.common.BuildConfig;
import com.jvup.common.model.entity.UserEntity;
import com.lzy.okgo.OkGo;
import com.lzy.okgo.cache.CacheEntity;
import com.lzy.okgo.cache.CacheMode;
import com.lzy.okgo.cookie.CookieJarImpl;
import com.lzy.okgo.cookie.store.SPCookieStore;
import com.lzy.okgo.https.HttpsUtils;
import com.lzy.okgo.interceptor.HttpLoggingInterceptor;
import com.lzy.okgo.model.HttpHeaders;

import java.util.HashMap;
import java.util.Map;
import java.util.UUID;
import java.util.concurrent.TimeUnit;
import java.util.logging.Level;

import okhttp3.OkHttpClient;

public class OkGoConfigHelper {


    public  static final HashMap<String, String> headerMap = new HashMap<>(6);

    private static String generateRandomUUID(Context context){
        String uuid_key = "uuid";
        String strUUID = CacheStorageUtil.queryString(uuid_key);
        if(TextUtils.isEmpty(strUUID)){
            strUUID = UUID.randomUUID().toString();
            CacheStorageUtil.save(uuid_key, strUUID);
        }
        return strUUID;
    }

    public  static void initHeader(Context context){
        headerMap.put("token", UserEntity.self.getToken());
        headerMap.put("platform", "android");
        headerMap.put("appVersion", AppHelper.getVersionName(context));
    }

    public  static void initOkGo(Application context){
        OkHttpClient.Builder builder = new OkHttpClient.Builder();

        if(BuildConfig.DEBUG) {
            HttpLoggingInterceptor loggingInterceptor = new HttpLoggingInterceptor("OkGo");
            //log打印级别，决定了log显示的详细程度
            loggingInterceptor.setPrintLevel(HttpLoggingInterceptor.Level.BODY);
            //log颜色级别，决定了log在控制台显示的颜色
            loggingInterceptor.setColorLevel(Level.INFO);
            builder.addInterceptor(loggingInterceptor);
        }

        //全局的读取超时时间
        builder.readTimeout(OkGo.DEFAULT_MILLISECONDS, TimeUnit.MILLISECONDS);
        //全局的写入超时时间
        builder.writeTimeout(OkGo.DEFAULT_MILLISECONDS, TimeUnit.MILLISECONDS);
        //全局的连接超时时间
        builder.connectTimeout(OkGo.DEFAULT_MILLISECONDS, TimeUnit.MILLISECONDS);

        //使用sp保持cookie，如果cookie不过期，则一直有效
        builder.cookieJar(new CookieJarImpl(new SPCookieStore(context)));

        //信任所有证书,不安全有风险
        HttpsUtils.SSLParams sslParams1 = HttpsUtils.getSslSocketFactory();
        builder.sslSocketFactory(sslParams1.sSLSocketFactory, sslParams1.trustManager);

        HttpHeaders headers = new HttpHeaders();
        for ( Map.Entry<String, String> entry : headerMap.entrySet()){
            headers.put(entry.getKey(), entry.getValue());
        }

        OkGo.getInstance().init(context)                        //必须调用初始化
                .setOkHttpClient(builder.build())               //必须设置OkHttpClient
                .setCacheMode(CacheMode.NO_CACHE)               //全局统一缓存模式，默认不使用缓存，可以不传
                .setCacheTime(CacheEntity.CACHE_NEVER_EXPIRE)   //全局统一缓存时间，默认永不过期，可以不传
                .setRetryCount(3)                               //全局统一超时重连次数，默认为三次，那么最差的情况会请求4次(一次原始请求，三次重连请求)，不需要可以设置为0
                .addCommonHeaders(headers);                     //全局公共头

    }

    public  static void refreshToken(){

        if(headerMap != null)
            headerMap.put("token", UserEntity.self.getToken());

        HttpHeaders headers = OkGo.getInstance().getCommonHeaders();
        if(headers == null) {
            headers = new HttpHeaders();
            headers.put("token", UserEntity.self.getToken());
            OkGo.getInstance().addCommonHeaders(headers);
        }else{
            headers.put("token", UserEntity.self.getToken());
        }
    }

    /**
     * 需要授权才能获取到
     */
    public  static void setDeviceUuidWithImei(String imei) {

        if (TextUtils.isEmpty(imei) || imei.equals("000000000000000")) {
            return;
        }
        if(headerMap != null)
            headerMap.put("uuid", imei);

        HttpHeaders headers = OkGo.getInstance().getCommonHeaders();
        if(headers == null) {
            headers = new HttpHeaders();
            headers.put("uuid", imei);
            OkGo.getInstance().addCommonHeaders(headers);
        }else{
            headers.put("uuid", imei);
        }

    }


}
